package org.petstore.web.servlet;

import org.petstore.domain.Account;
import org.petstore.service.CartService;
import org.petstore.service.CatalogService;
import org.petstore.service.impl.CartServiceImpl;
import org.petstore.util.Cart;
import org.petstore.web.servlet.util.MyUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import static org.petstore.web.servlet.util.ServletUtil.LOGIN_FORM;

public class ViewCartServlet extends HttpServlet {
    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";

    private final CartService cartService = MyUtil.getApplicationContext().getBean("cartService", CartService.class);

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        Account loginUser = (Account) session.getAttribute("loginUser");
        if (loginUser == null) {
            request.setAttribute("msg", "请先登录");
            request.getRequestDispatcher(LOGIN_FORM).forward(request, response);
            return;
        }
        if (cart == null) {
            cart = cartService.getCartByName(loginUser.getUsername());
            session.setAttribute("cart", cart);
        }
        request.getRequestDispatcher(VIEW_CART).forward(request, response);
    }
}
